package com.gastronomy.service.impl;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.multipart.MultipartFile;

import com.gastronomy.constant.Constant;
import com.gastronomy.dao.DishesDao;
import com.gastronomy.dao.UserDao;
import com.gastronomy.entity.DishesEntity;
import com.gastronomy.entity.User;
import com.gastronomy.service.DishesService;
import com.gastronomy.util.SpringUtil;
import com.github.pagehelper.PageHelper;

@Service("dishesService")
public class DishesServiceImpl implements DishesService {

	@Autowired
	private DishesDao dishesDao;
	
	
	@Autowired
	private UserDao userDao;
	/**
	 * 分页查询用户下的所有菜肴
	 * 
	 * @param user
	 * @return
	 */
	@Override
	public List<DishesEntity> listDishes(User user, String currentPage,
			Integer pageSize) {
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();

		
		if (user == null) {
			return dishesEntities;
		}
		
		User currentUser = userDao.findUserByNameAndPwd(user.getUserName(), user.getPassword());
		if(currentUser == null || currentUser.getRole().getId()!=3){
			return dishesEntities;
		}
		Integer page = 1;
		try {
			page = Integer.parseInt(currentPage);
		} catch (Exception e) {
			System.out.println("转化错误");
			page = 1;
		}
		PageHelper.startPage(page, pageSize);

		dishesEntities = dishesDao.listDishes(currentUser.getUserId());
		return dishesEntities;
	}
	/**
	 * 查询用户下的所有菜肴
	 * 不分页
	 * @param user
	 * @return
	 */
	@Override
	public List<DishesEntity> listAllDishesByUserId(int userId) {
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();
		User user = userDao.queryUserById(userId);
		if(user == null || user.getRole().getId()!=3){
			return dishesEntities;
		}
		dishesEntities = dishesDao.listDishes(userId);
		return dishesEntities;
	}
	

	@Override
	public DishesEntity queryDishesEntity(String dishesId) {
		
		if(dishesId == null || dishesId.trim().equals(""))
			return null;
		
		Integer id = null;
		try {
			id = Integer.parseInt(dishesId);
		} catch (Exception e) {
			return null;
		}
		DishesEntity dishesEntity = dishesDao.queryDishesEntity(id);
		return dishesEntity;
	}

	@Override
	public Map<String, String> underShelf(String dishIds) {
		Map<String, String> resultMap = new HashMap<String,String>();
		if(dishIds == null || dishIds.trim().equals("")){
			resultMap.put("underShelfResult", "FAIL");
			resultMap.put("errorMsg", "请选择您要下架的美食");
			return resultMap;
		}
		
		String [] ids = dishIds.split(",");
		try {
			dishesDao.underShelfs(ids);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			resultMap.put("underShelfResult", "FAIL");
			resultMap.put("errorMsg", "美食下架操作失败");
		}
		resultMap.put("underShelfResult", "SUCCESS");
		return resultMap;
		
	}
	@Override
	public void updateDishesFocus(DishesEntity dishesEntity) {
		dishesDao.updateDishesFocus(dishesEntity);
	}
	@Override
	public List<DishesEntity> listAllDishes(String currentPage) {
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();
		sort(currentPage,8);
		dishesEntities = dishesDao.listAllDishes();
		return dishesEntities;
	}

	@Override
	public List<DishesEntity> listDishesByVisitCount(String currentPage) {
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();
		sort(currentPage);
		dishesEntities = dishesDao.listDishesByVisitCount();
		return dishesEntities;
	}

	@Override
	public List<DishesEntity> listDishesByPrice(String currentPage) {
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();
		sort(currentPage);
		dishesEntities = dishesDao.listDishesByPrice();
		return dishesEntities;
	}

	@Override
	public List<DishesEntity> listDishesByCreateTime(String currentPage) {
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();
		sort(currentPage);
		dishesEntities = dishesDao.listDishesByCreateTime();
		return dishesEntities;
	}

	public void sort(String currentPage){
		Integer page = 1;
		try {
			if(currentPage==null||currentPage.equals("")){
				currentPage = "1";
			}
			page = Integer.parseInt(currentPage);
		} catch (Exception e) {
			System.out.println("转化错误");
			page = 1;
		}
		PageHelper.startPage(page, 9);
	}
	public void sort(String currentPage,int pageSize){
		Integer page = 1;
		try {
			if(currentPage==null||currentPage.equals("")){
				currentPage = "1";
			}
			page = Integer.parseInt(currentPage);
		} catch (Exception e) {
			System.out.println("转化错误");
			page = 1;
		}
		PageHelper.startPage(page, pageSize);
	}

	@Override
	public List<DishesEntity> sortDishes(String type, String sortType, String foodName, String currentPage ,int pageSize) {
		//type==A，查询
		//type==B，排序，sortType==1：按访问量排序，sortType==2：按价格排序，sortType==3：按发布时间排序(初始化时默认按发布时间排序)
		//type==C，加载更多
		List<DishesEntity> dishesEntities = new ArrayList<DishesEntity>();
		if(foodName==null){
			foodName = "";
		}
		if(sortType==null){
			sortType = "createTime";
		}
		if(type.equals("A")||type.equals("B")){
			currentPage = "1";
		}
		sort(currentPage,pageSize);
		if(sortType.equals("focuse")){
			dishesEntities = dishesDao.sortDishesByFocuse(foodName);
		}else if(sortType.equals("price")){
			dishesEntities = dishesDao.sortDishesByPrice(foodName);
		}else if(sortType.equals("createTime")){
			dishesEntities = dishesDao.sortDishesByCreateTime(foodName);
		}
		return dishesEntities;
	}
	@Override
	public Map<String, String> saveShesEntity(DishesEntity dishesEntity,
			MultipartFile picFile, User user) {

		Map<String, String> map = new HashMap<String, String>();
		if(user.getRole().getId()!=3){
			map.put("result", "FAIL");
			map.put("error_msg", "您没有权限发布新菜品");
			return map;
		}
		String newFileName = saveUploadPic(user,picFile);
		if(newFileName.equals("FAIL")){
			map.put("result", "FAIL");
			map.put("error_msg", "出现未知错误，请联系系统管理员！");
			return map;
		}
		dishesEntity.setTopPic(File.separator+Constant.PIC_PATH+File.separator+user.getUserName()+File.separator+newFileName);
		dishesEntity.setScode(0.00);
		dishesEntity.setCreateTime(new Timestamp(new Date().getTime()));
		dishesEntity.setUser(user);
		dishesDao.saveDishesEntity(dishesEntity);
		map.put("result", "SUCCESS");
		return map;
	}
	@Override
	public String saveUploadPic(User user,MultipartFile picFile){
		String newFileName = "";
		try {
			// 原始名称
			String originalFilename = picFile.getOriginalFilename();
			// 上传图片
			if (picFile != null && originalFilename != null
					&& originalFilename.length() > 0) {
				// 存储图片的物理路径
				String pic_path = SpringUtil.getWebInfAbsolutePath()+File.separator+Constant.PIC_PATH+File.separator+user.getUserName();
				File file = new File(pic_path);
				if(!file.exists())
					file.mkdirs();
				// 新的图片名称
				newFileName = user.getUserName()
						+ "_"
						+ new Date().getTime()
						+ originalFilename.substring(originalFilename
								.lastIndexOf("."));
				// 新图片
				File newFile = new File(pic_path, newFileName);
				// 将内存中的数据写入磁盘
				picFile.transferTo(newFile);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "FAIL";
		}
		return newFileName;
	}
}
